using System;
using System.Linq;
using DataScripter.Database;

namespace DataScripter.Scripting.Compare.InsideSqlServer.Data
{
    public class RecordsDeleter
    {
        private Db Db { get; set; }
        private IDatabaseStructure LeftDatabase { get; set; }
        private IDatabaseStructure RightDatabase { get; set; }
        private ITableStructure LeftTable { get; set; }
        private ITableStructure RightTable { get; set; }

        public String Sql { get; private set; }

        public RecordsDeleter(Db db, IDatabaseStructure leftDatabase, ITableStructure leftTable, IDatabaseStructure rightDatabase, ITableStructure rightTable)
        {
            Db = db;
            LeftDatabase = leftDatabase;
            LeftTable = leftTable;
            RightDatabase = rightDatabase;
            RightTable = rightTable;

            Sql = ConstructSql();
        }


        private string ConstructSql()
        {
            // Build sql for identical records
            string fieldList = string.Join(",", LeftTable.PrimaryKeyFields.Select(primaryKeyField => "[A]." + primaryKeyField.ColumnName).ToArray());
            string joinClause = string.Join(" AND ", LeftTable.PrimaryKeyFields.Select(primaryKeyField => "A." + primaryKeyField.ColumnName + "=" + "B." + primaryKeyField.ColumnName).ToArray());
            string insertSql = string.Format("INSERT INTO {4}.{5}.{6} SELECT [A].* FROM {1}.{2}.{3} A INNER JOIN {4}.{5}.{6} B ON {7} ORDER BY {0}",
                                             fieldList,
                                             LeftDatabase.Database, LeftTable.SchemaName, LeftTable.TableName,
                                             RightDatabase.Database, RightTable.SchemaName, RightTable.TableName,
                                             joinClause);

            return insertSql;
        }

        public void DeleteRecords()
        {
            Db.ExecuteNonQuery(Sql);
        }
    }
}